package cn.itsource.basic.util;

import cn.itsource.basic.domain.BaseTreeNode;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;


@Slf4j
public class TreeUtil {


    public static <T extends BaseTreeNode> List<T> getTree(List<T> list) {
//                List<T> listParentNode = new ArrayList<>();
//                for (int i = 0; i < list.size(); i++) {
//                    //拿到每条数据
//                    T t = list.get(i);
//                    //判断是否为顶级节点
//                    if (t.getParentId() == null) {
//                        //是顶级节点的情况
//                        listParentNode.add(t);
//                    }
//                }
//                for (T t : listParentNode) {
//                    t.setChildren(getChildList(t, list));
//                }
//                return listParentNode;

        Map<Long, T> map = list.stream().collect(Collectors.toMap(m -> m.getId(), s -> s));
        List<T> result = new LinkedList<>();
        for (Long key : map.keySet()) {
            T current = map.get(key);
            if (current.getParentId() == null) {
                result.add(current);
            } else {
                T parent = map.get(current.getParentId());
                List<T> children = Optional.ofNullable(parent.getChildren()).orElse(new LinkedList<T>());
                children.add(current);
                parent.setChildren(children);
            }
        }
        return result;
    }

    /**
     * 获取子节点
     *
     * @param curentNode 当前节点
     * @param list       所有节点集合
     * @param <T>
     * @return
     */
    public static <T extends BaseTreeNode> List<T> getChildList(T curentNode, List<T> list) {

        List<T> childList = new ArrayList<>();
        //寻找所有节点
        for (T t : list) {
            //如果当前节点和我寻找的节点是同一个 或者 是顶级节点 那么肯定不是当前节点的子节点
            if (t == curentNode || t.getParentId() == null) {
                continue;
            }
            //寻找子节点
            if (curentNode.getId() == t.getParentId()) {
                //如果寻找到子节点,那么将子节点存储起来
                t.setChildren(getChildList(t, list));
                childList.add(t);
            }
        }
//        curentNode.setChildren(childList);
        return childList.size() == 0 ? null : childList;
    }
}
